package cn.hfatec.app;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * @author: panwb
 *
 * Date: 2015/3/3
 * Time: 19:05
 */
public class AppContext implements ApplicationContextAware {

    private static ApplicationContext context;

    public static <T> T getBean(String name,Class<T> t) {
        Object bean = context.getBean(name);
        if (t.isAssignableFrom(bean.getClass())) {
            return t.cast(bean);
        } else {
            return null;
        }
    }

    public static <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }

    public static <T>Map<String,T> getBeansOfType(Class<T> t) {
        return context.getBeansOfType(t);
    }

    public static Map<String,Object> getBeansWithAnnotation(Class<? extends Annotation> clazz) {
        return context.getBeansWithAnnotation(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AppContext.context = applicationContext;
    }
}
